import { computed, type Ref } from 'vue'
import { useTreeStore, type ProjectTreeNode } from '@/store/modules/tree'

export interface SimpleNodeOption { key: string; name: string }

/**
 * 在指定 key 节点的祖先中，找到最近的 parentType 节点，
 * 然后在其 children 下查找 type=targetType 的所有节点。
 * @param projectIdRef 项目ID
 * @param parentType 父级类型（如 partChildren）
 * @param targetType 目标类型（如 setChildren）
 * @param key 当前节点 key
 */
export function useFindNodesByParentTypeAndType(
  projectIdRef: Ref<string | number | null | undefined>,
  parentType: string,
  targetType: string,
  key: string
) {
  const treeStore = useTreeStore()
  const result = computed<SimpleNodeOption[]>(() => {
    const pid = projectIdRef.value
    if (pid == null) return []
    const tree = treeStore.getTree(pid)
    if (!Array.isArray(tree) || !tree.length) return []
    // 1. 找到当前节点的祖先路径（不包含自己）
    function findAncestorsByKey(nodes: ProjectTreeNode[], key: string): ProjectTreeNode[] {
      let path: ProjectTreeNode[] = []
      function dfs(node: ProjectTreeNode, ancestors: ProjectTreeNode[]): boolean {
        if (node.key === key) {
          path = ancestors // 不包含自己
          return true
        }
        for (const child of node.children || []) {
          if (dfs(child, [...ancestors, node])) return true
        }
        return false
      }
      for (const root of nodes) {
        if (dfs(root, [])) break
      }
      return path
    }
    const ancestors = findAncestorsByKey(tree, key)
    // 2. 从最近的祖先中查找 parentType
    let parentNode: ProjectTreeNode | null = null
    for (let i = ancestors.length - 1; i >= 0; i--) {
      if (ancestors[i].type === parentType) {
        parentNode = ancestors[i]
        break
      }
    }
    if (!parentNode) return []
    // 3. 在 parentNode.children 下查找 type=targetType 的所有节点
    function collectTargetType(nodes: ProjectTreeNode[], targetType: string): SimpleNodeOption[] {
      const result: SimpleNodeOption[] = []
      for (const node of nodes) {
        if (node.type === targetType && node.name) {
          result.push({ key: node.key, name: node.name })
        }
        if (node.children?.length) {
          result.push(...collectTargetType(node.children, targetType))
        }
      }
      return result
    }
    return collectTargetType(parentNode.children, targetType)
  })
  return { result }
}
